<template>
  <div class="weightItem">
    <van-nav-bar
      :title="$route.meta.title"
      left-arrow
      :border="false"
      @click-left="onClickLeft"
      @click-right="onClickRight"
      class="nav-bar"
    >
      <template #right>
        <van-icon name="search" size="24" />
      </template>
    </van-nav-bar>
    <!-- <div class="search">
      <van-search
        v-model="searchValue"
        show-action
        placeholder="请输入搜索关键词"
        left-icon="none"
      >
        <template #left>
          <van-icon
            style="padding: 0.1rem"
            name="scan"
            @click="openScan()"
            size="30"
          />
        </template>
        <template #action>
          <div style="color: #1e9fff" @click="onSearch">查询</div>
        </template>
      </van-search>
    </div> -->
    <div class="item-style">
      <!-- <div style="display: flex; justify-content: space-between">
        <van-tag plain type="primary" style="margin: 20px 10px 10px 10px"
          >检索信息</van-tag
        >
        <van-button
          size="mini"
          type="info"
          icon="search"
          style="
            margin-right: 25px;
            margin-top: 10px;
            padding: 0px 10px;
            background: #49bbef;
          "
          @click="onSearch('handleSearch')"
          >查询</van-button
        >
      </div> -->
      <van-row gutter="20" type="flex" justify="left" align="center">
        <!-- <van-col
          span="4"
          style="
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
          "
          @click="openScan('device')"
        >
          <van-icon name="scan" /><span>称量仪器</span>
        </van-col> -->
        <van-col span="12">
          <van-field
            v-model="deviceName"
            name="deviceName"
            label="称量仪器"
            readonly
            placeholder="请选择称量仪器"
            left-icon="scan"
            input-align="center"
            @click-left-icon="openScan('device')"
            class="deviceStyle"
          >
            <template #input>
              <device-name
                :deviceName="deviceName"
                @change="getDeviceCode"
              ></device-name>
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="instCode"
            name="instCode"
            label="仪器编号"
            readonly
            input-align="center"
          >
          </van-field>
        </van-col>
      </van-row>

      <van-row gutter="20" type="flex" justify="left" align="center">
        <van-col span="12">
          <van-field
            v-model="materialType"
            name="materialType"
            label="物料类型"
            input-align="center"
            left-icon="scan"
            @click-left-icon="openScan('material')"
            class="deviceStyle"
          >
            <template #input>
              <material-type
                :materialTypeName="materialTypeName"
                v-model="materialType"
              />
            </template>
          </van-field>
        </van-col>
        <!-- <van-col span="12">
          <van-field
            v-model="materialType"
            name="materialType"
            label="物料类型"
            input-align="center"
          >
            <template #input>
              <material-type
                :materialTypeName="materialTypeName"
                v-model="materialType"
              />
            </template>
          </van-field>
        </van-col> -->
        <van-col span="12">
          <van-field
            v-model="materialCode"
            name="materialCode"
            label="物料名称"
            input-align="center"
          >
            <template #input>
              <material-name
                :materialName="materialName"
                :materialType="materialType"
                v-model="materialCode"
              />
            </template>
          </van-field>
        </van-col>
        <!-- <van-col span="12" style="padding-right: 10px">
          <van-field
            v-model="batch"
            name="batch"
            label="批号"
            input-align="center"
          >
          </van-field>
        </van-col> -->
        <van-col span="12" style="padding-right: 10px">
          <van-field
            v-model="batch"
            name="batch"
            label="称重批次"
            clickable
            input-align="center"
          >
            <template #input>
              <batch-list
                :batchIdArr="batchIdArr"
                :batchId="batchId"
                @chooseValue="updataBatch"
              >
              </batch-list>
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="deviceItemCode"
            name="deviceItemCode"
            label="称重项目:"
            readonly
            placeholder="请选择称重项目"
          >
            <template #input>
              <mult-select
                :dataList="deviceItemArr"
                @chooseValue="updataDeviceItemCode"
              />
            </template>
          </van-field>
        </van-col>
      </van-row>
      <div style="display: flex; justify-content: space-between">
        <!-- <van-tag plain type="primary" style="margin: 20px 10px 10px 10px"
          >基础信息</van-tag
        > -->
        <!-- <van-button
          size="small"
          type="info"
          style="
            float: right;
            margin-right: 20px;
            margin-top: 10px;
            height: 0.58667rem;
            color: #fff;
            padding: 0 5px;
            background: #49bbef;
          "
          @click="resetDevice()"
          >重新连接</van-button
        > -->
        <van-loading
          v-if="connectState"
          type="spinner"
          style="float: right; margin-right: 20px; margin-top: 15px"
          color="#1989fa"
          size="30px"
        />
      </div>

      <van-tag plain type="primary" style="margin: 20px 10px 10px 10px"
        >检验列表</van-tag
      >
      <div class="checkItem">
        <van-list :finished="finished" finished-text="暂无数据">
          <van-swipe-cell v-for="(v, i) in itemList" :key="i" ref="swipecell">
            <van-cell
              title-class="custom-title"
              value-class="custom-value"
              label-class="custom-label"
            >
              <template #title>
                <div class="titleStyle">
                  <span class="custom-title">{{ v.materialName }}</span>
                  <div class="controlBtn">
                    <!-- <van-button
                      icon="scan"
                      style="padding: 0px 10px"
                      ref="sampleConfirm"
                      @click="openScan('sample', v, i)"
                      >样品确认</van-button
                    > -->
                    <button
                      ref="startWeight"
                      :disabled="ishandle"
                      @click="getWeightNum(v, i)"
                    >
                      开始
                    </button>

                    <button
                      v-if="v.weighMode != '1' && v.weighMode != '25'"
                      @click="resetItem(v)"
                    >
                      重称
                    </button>
                    <button
                      v-if="v.weighMode != '1' && v.weighMode != '25'"
                      @click="saveWeightItem(v, v.weighValue, '结果数据', 'T')"
                    >
                      完成
                    </button>
                    <button
                      v-if="v.weighMode == '1' || v.weighMode == '25'"
                      @click="
                        saveWeightItem(
                          v,
                          v.weighData[v.weighData.length - 1].testValue,
                          '结果数据',
                          'T'
                        )
                      "
                    >
                      完成
                    </button>
                  </div>
                </div>
              </template>
              <template #label>
                <!-- <div>编号：{{ v.taskItemNo }}</div> -->
                <div v-if="v.weighMode == '1'">模式：称重模式</div>
                <div v-if="v.weighMode == '10'">模式：皮重、毛重、净重模式</div>
                <!-- <div v-if="v.weighMode == '15'">模式：皮重、净重、毛重模式</div> -->
                <div v-if="v.weighMode == '20'">模式：减重模式(普通)</div>
                <div v-if="v.weighMode == '25'">模式：减重模式(特殊)</div>
                <!-- <div v-if="v.weighMode == '40'">模式：干燥失重模式</div> -->
                <!-- <div v-if="v.weighMode == '50'">模式：炽灼残渣模式</div> -->
                <!-- <div v-if="weighData.length > 3"> -->
                <div>称重项目：{{ v.attributeName }}</div>
                <div>批号：{{ v.batchID }}</div>
                <div class="spanStyle">
                  <!-- if((j+1)%3==1){
                  <div>编号：{{ v.taskItemNo }}</div>
                  } -->
                  <div v-if="v.weighMode == '1'">
                    <div class="style1">
                      重<i style="display: inline-block; width: 19.2px"></i
                      >量：<span>{{
                        v.weighData[v.weighData.length - 1].testValue
                      }}</span>
                    </div>
                  </div>
                  <div v-if="v.weighMode == '25'">
                    <div class="style1">
                      重<i style="display: inline-block; width: 19.2px"></i
                      >量：<span>{{
                        v.weighData[v.weighData.length - 1].testValue
                      }}</span>
                    </div>
                  </div>
                  <div v-if="v.weighMode == '10'">
                    <div class="style1">
                      皮重：<span>{{ v.weighData[0].testValue }}</span>
                    </div>
                    <div class="style1">
                      毛重：<span>{{ v.weighData[1].testValue }}</span>
                    </div>
                    <div class="style1">
                      净重：<span>{{ v.weighValue }}</span>
                    </div>
                  </div>
                  <!-- <div v-if="v.weighMode == '15'">
                  <div class="style1">
                    皮重：<span>{{ v.weighData[0].testValue }}</span>
                  </div>
                  <div class="style1">
                    净重：<span>{{ v.weighData[1].testValue }}</span>
                  </div>
                  <div class="style1">
                    毛重：<span>{{ v.weighValue }}</span>
                  </div>
                </div> -->
                  <div v-if="v.weighMode == '20'">
                    <div class="style1">
                      使用前：<span>{{ v.weighData[0].testValue }}</span>
                    </div>
                    <div class="style1">
                      使用后：<span>{{ v.weighData[1].testValue }}</span>
                    </div>
                    <div class="style1">
                      结<i style="display: inline-block; width: 19.2px"></i
                      >果：<span>{{ v.weighValue }}</span>
                    </div>
                  </div>
                  <!-- <div v-if="v.weighMode == '40'">
                  <div v-for="(t, j) in v.weighData" :key="j">
                    <div v-if="j == 0" class="style1">
                      恒重前：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j == 1" class="style1">
                      恒重后：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j == 2" class="style1">
                      净<i style="display: inline-block; width: 19.2px"></i
                      >重：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j > 2" class="style1">
                      CN{{ j - 2 }}
                      <i style="display: inline-block; width: 19.2px"></i
                      >：<span>{{ t.testValue }}</span>
                    </div>
                  </div>
                  <div class="style1">
                    结<i style="display: inline-block; width: 19.2px"></i
                    >果：<span>{{ v.weighValue }}%</span>
                  </div>
                </div>
                <div v-if="v.weighMode == '50'">
                  <div v-for="(t, j) in v.weighData" :key="j">
                    <div v-if="j == 0" class="style1">
                      恒重前：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j == 1" class="style1">
                      恒重后：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j == 2" class="style1">
                      净<i style="display: inline-block; width: 19.2px"></i
                      >重：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j > 2" class="style1">
                      CN{{ j - 2 }}
                      <i style="display: inline-block; width: 19.2px"></i
                      >：<span>{{ t.testValue }}</span>
                    </div>
                  </div>
                  <div class="style1">
                    结<i style="display: inline-block; width: 19.2px"></i
                    >果：<span>{{ v.weighValue }}%</span>
                  </div>
                </div> -->
                </div>
              </template>
            </van-cell>
            <template #right>
              <van-button
                square
                block
                type="danger"
                style="height: 100%"
                text="删除"
                @click.stop="delItem(v, i)"
              />
            </template>
          </van-swipe-cell>
        </van-list>
      </div>
    </div>
    <div class="scan" v-if="scanShow">
      <div id="bcid">
        <div style="height: 40%"></div>
        <p class="tip">...载入中...</p>
      </div>
      <footer>
        <button @click="closeModel">退出</button>
      </footer>
    </div>
  </div>
</template>

<script>
import {
  NavBar,
  Cell,
  CellGroup,
  Notify,
  Col,
  Row,
  DropdownMenu,
  DropdownItem,
  Icon,
  Tag,
  Button,
  Popup,
  Field,
  Picker,
  List,
  SwipeCell,
  Dialog,
  Loading,
  Search,
} from "vant";
import {
  getTestByTestId,
  getTaskSelect, //回去项目code
  saveTaskItemData, //保存项目
  taskItemWeighAgain,
  saveReckonTaskItemData,
  DeleteTaskAttribute,
  GetTaskItemsTwo,
  GetTaskBatchIDs, //批次接口
} from "@/api/base";
import { GetAttributesByMaterialCode } from "@/api/check";
import { to } from "@/utils";
import DeviceName from "./components/DeviceName";
import MaterialType from "./components/MaterialType";
import MaterialName from "./components/MaterialName";
import MultSelect from "./components/MultSelect";
import BatchList from "./components/BatchList";
let scan = null;
export default {
  name: "weightItem",
  components: {
    [NavBar.name]: NavBar,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Notify.name]: Notify,
    [Col.name]: Col,
    [Row.name]: Row,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [List.name]: List,
    [SwipeCell.name]: SwipeCell,
    [Dialog.name]: Dialog,
    [Loading.name]: Loading,
    [Search.name]: Search,
    DeviceName,
    MaterialType,
    MaterialName,
    MultSelect,
    BatchList,
  },
  data() {
    return {
      finished: false,
      token: "",
      instCode: "", //编号
      deviceName: "",
      // weight: "",
      // unity: "",
      scanShow: false,
      ws: "",
      socket: "",
      socketUrl: "",
      gDomain: "",
      scanType: "",
      scanObj: {},
      timer: null,
      itemList: [],
      weightBatch: "",
      weightBatchArr: [],
      weightNumber: "",
      weightItemObj: {},
      weightValue: "",
      weightValue1: "", //过程称量
      weightValue2: "", //过程称量
      weightValue3: "",
      weightValue4: "",
      weightValue5: "",
      textValue: "", //结果称量
      testNumber: 0, //称量次数
      weightPort: "",
      decimalNum: 4,
      ishandle: false,
      connectState: false,
      searchValue: "", //查询字段
      materialType: "",
      materialTypeName: "",
      materialCode: "",
      materialName: "",
      batch: "",
      deviceArr: [], //多选称重项目编码
      deviceItemCode: "", //称重项目编号
      deviceItemName: "",
      deviceItemArr: [],
      sampleObj: {},
      sampleNum: "",
      batchDataArr: [],
      batchId: "",
      batchIdArr: [],
    };
  },
  watch: {
    instCode(val) {
      this.socketUrl = "ws://" + this.weightPort + "/" + val;
      if (typeof this.socket.close == "function") {
        this.socket.close();
      }
      if (val) {
        this.connectState = true;
        this.init();
      }
    },
    testNumber(val) {
      if (val) {
        if (
          this.weightItemObj.weighMode == "10" ||
          // this.weightItemObj.weighMode == "15" ||
          this.weightItemObj.weighMode == "20"
        ) {
          if (val == 1) {
            this.weightValue1 = this.weightValue;
            this.saveWeightItem(
              this.weightItemObj,
              this.weightValue1,
              "过程数据"
            );
          } else if (val == 2) {
            this.weightValue2 = this.weightValue;
            if (this.weightItemObj.weighMode == "10") {
              this.textValue = parseFloat(
                Number(this.weightValue2) - Number(this.weightValue1)
              );
            } else if (this.weightItemObj.weighMode == "20") {
              this.textValue = parseFloat(
                Number(this.weightValue1) - Number(this.weightValue2)
              );
            }
            // else if (this.weightItemObj.weighMode == "15") {
            //   this.textValue = parseFloat(
            //     (Number(this.weightValue1) + Number(this.weightValue2)).toFixed(
            //       5
            //     )
            //   );
            // }
            this.textValue = this.getDecimaZero(
              this.textValue,
              this.decimalNum
            );
            this.saveWeightItem(
              this.weightItemObj,
              this.weightValue2,
              "过程数据"
            );
          }
        }
        //  else if (this.weightItemObj.weighMode == "40") {
        //   if (val == 1) {
        //     this.weightValue1 = this.weightValue;
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue,
        //       "过程数据"
        //     );
        //   } else if (val == 2) {
        //     this.weightValue2 = this.weightValue;
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue,
        //       "过程数据"
        //     );
        //   } else if (val == 3) {
        //     this.weightValue3 = this.weightValue;
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue3,
        //       "过程数据"
        //     );
        //   } else {
        //     this.weightValue4 = this.weightValue;
        //     this.textValue = parseFloat(
        //       (
        //         ((Number(this.weightValue3) +
        //           Number(this.weightValue2) -
        //           Number(this.weightValue4)) *
        //           100) /
        //         Number(this.weightValue3)
        //       ).toFixed(5)
        //     );
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue4,
        //       "过程数据"
        //     );
        //   }
        // }
        // else if (this.weightItemObj.weighMode == "50") {
        //   if (val == 1) {
        //     this.weightValue1 = this.weightValue;
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue,
        //       "过程数据"
        //     );
        //   } else if (val == 2) {
        //     this.weightValue2 = this.weightValue;
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue,
        //       "过程数据"
        //     );
        //   } else if (val == 3) {
        //     this.weightValue3 = this.weightValue;
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue3,
        //       "过程数据"
        //     );
        //   } else if (val == 4) {
        //     this.weightValue4 = this.weightValue;
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue4,
        //       "过程数据"
        //     );
        //   } else {
        //     this.weightValue5 = this.weightValue;
        //     this.textValue = parseFloat(
        //       (
        //         ((Number(this.weightValue5) - Number(this.weightValue2)) *
        //           100) /
        //         Number(this.weightValue3)
        //       ).toFixed(5)
        //     );
        //     this.saveWeightItem(
        //       this.weightItemObj,
        //       this.weightValue5,
        //       "过程数据"
        //     );
        //   }
        // }
        else if (this.weightItemObj.weighMode == "1") {
          this.saveWeightItem(this.weightItemObj, this.weightValue, "过程数据");
        } else if (this.weightItemObj.weighMode == "25") {
          this.saveWeightItem(
            this.weightItemObj,
            Math.abs(this.weightValue),
            "过程数据"
          );
        }
      }
    },
    materialCode(val) {
      if (val) {
        // this.getItemData(val);
        this.getBatchData(val); //批次信息
      }
    },
  },
  mounted() {
    this.gDomain = localStorage.getItem("domainKey");
    this.token = localStorage.getItem("tokenKey");
    // this.getMaterialType();
    if (this.gDomain.includes("//")) {
      var dStr = this.gDomain.split("//")[1];
      if (dStr.includes(":")) {
        this.weightPort = dStr.split(":")[0] + ":10002";
        // this.weightPort = dStr.split(":")[0] + ":20001";
      } else {
        this.weightPort = dStr;
      }
    }
    // this.getItemCode();
    this.onSearch("one"); //默认查询
    this.getBatchData(""); //批次信息
  },
  methods: {
    onClickLeft() {
      if (this.socket && this.socket != "") {
        this.socket.close();
      }
      if (scan && scan != "") {
        scan.close();
      }
      this.$router.replace({ name: "home" });
    },
    onClickRight() {
      this.onSearch();
    },
    resetDevice() {
      this.socketUrl = "ws://" + this.weightPort + "/" + this.instCode;
      this.init();
    },
    openScan(type, v, i) {
      var that = this;
      this.scanType = type;
      this.scanShow = true;
      if (type == "sample") {
        this.sampleObj = v;
        this.sampleNum = i;
        var classArr = this.$refs.sampleConfirm;
        var classArr1 = this.$refs.startWeight;
        if (classArr && classArr.length > 0) {
          classArr.map((item, index) => {
            item.style.background = "#cdcbcb";
            item.style.color = "#323233";
            classArr1[index].style.background = "#cdcbcb";
            classArr1[index].style.color = "#323233";
            classArr1[index].disabled = true;
          });
        }
      }
      this.timer = setTimeout(that.startRecognize, 500);
    },
    startRecognize() {
      var that = this;
      this.timer = null;
      if (!window.plus) return;
      scan = new plus.barcode.Barcode("bcid");
      scan.onmarked = onmarked;
      scan.start();
      function onmarked(type, result, file) {
        switch (type) {
          case plus.barcode.QR:
            type = "QR";
            break;
          case plus.barcode.EAN13:
            type = "EAN13";
            break;
          case plus.barcode.EAN8:
            type = "EAN8";
            break;
          default:
            type = "其它" + type;
            break;
        }

        scan.close();
        that.scanShow = false;
        if (that.scanType == "device") {
          var str = decodeURIComponent(result);
          var strObj = JSON.parse(str);
          that.deviceName = strObj.equipmentName;
          that.instCode = strObj.equipmentCode;
        } else if (that.scanType == "material") {
          //或去物料类型
          that.getScanType(JSON.parse(result).testID);
        } else if (that.scanType == "sample") {
          that.getScanType(JSON.parse(result).testID);
        }
      }
    },
    closeModel() {
      this.scanShow = false;
      if (!window.plus) return;
      scan.close();
    },
    getDeviceCode(val) {
      this.deviceName = val.text;
      this.instCode = val.value;
    },
    async getScanType(id) {
      var params = {
        queryModel: {
          Code: id,
          Token: this.token,
        },
      };
      const [err, res] = await to(getTestByTestId(params));
      this.scanObj = res.Result;
      this.materialName = "";
      if (this.scanType == "material") {
        this.materialName = res.Result.materialName;
        this.materialType = res.Result.materialType;
        this.materialCode = res.Result.materialCode;
        this.materialTypeName = res.Result.materialTypeName;
        this.batchId = res.Result.batchID;
        this.batch = res.Result.batchID;
        this.testID = res.Result.testID;
      }

      // if (this.materialType && this.materialType == res.Result.materialType) {
      //   this.materialName = res.Result.materialCode;
      //   this.batchID = res.Result.batchID;
      // } else {
      //   this.materialType = res.Result.materialType;
      // }

      if (this.scanType == "sample") {
        if (
          this.scanObj.materialCode == this.sampleObj.materialCode &&
          this.scanObj.batchID == this.sampleObj.batchID &&
          this.scanObj.testID == this.sampleObj.testID
        ) {
          var classArr = this.$refs.sampleConfirm;
          var classArr1 = this.$refs.startWeight;
          classArr[this.sampleNum].style.background = "#49bbef";
          classArr[this.sampleNum].style.color = "#fff";
          classArr1[this.sampleNum].disabled = false;
        }
      }
    },
    onFinish({ selectedOptions }) {
      this.showPicker = false;
      var len = selectedOptions.length;
      var toDetail = selectedOptions[len - 1];
      this.recordName = toDetail.text;
      this.recordCode = toDetail.value;
    },
    init: function () {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.socketUrl);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        //关闭链接
        this.socket.onclose = this.close;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      console.log("socket连接成功");
      Notify({ type: "success", message: "天平连接成功" });
      this.connectState = false;
    },
    error: function () {
      console.log("连接错误");
      Notify({ type: "danger", message: "天平连接失败" });
      this.connectState = false;
    },
    getMessage: function (msg) {
      var weightMsg = JSON.parse(msg.data).message;
      if (weightMsg) {
        if (weightMsg.includes("连接成功")) {
          // this.ishandle = false;
          Notify({ type: "success", message: weightMsg });
        } else {
          // this.ishandle = true;
          Notify({ type: "danger", message: weightMsg });
        }
      } else {
        this.testNumber++;
        this.weightValue = JSON.parse(msg.data).weight;
        var weightStr = this.weightValue.toString();
        if (weightStr.indexOf(".")) {
          this.decimalNum = weightStr.split(".")[1].length;
        }
      }
      this.connectState = false;

      // console.log(this.testNumber, this.weightValue);
      // this.unity = JSON.parse(msg.data).unity;
    },
    close() {
      console.log("关闭链接");
      this.connectState = false;
    },
    //获取项目列表
    getItemCode: function () {
      var params = {
        Token: this.token,
        search: [""],
      };
      getTaskSelect(params)
        .then((response) => {
          if (response.ErrorCode == 0) {
            this.weightBatchArr = response.Result;
          } else {
            Notify({ type: "danger", message: response.ErrorMsg });
          }
        })
        .catch(() => {});
    },
    getWeightNum: function (v, i) {
      this.testNumber = 0;
      var that = this;
      this.weightItemObj = v;
      var classArr = this.$refs.startWeight;
      classArr.map((item) => {
        item.style.background = "#cdcbcb";
        item.style.color = "#323233";
      });
      classArr[i].style.background = "#49bbef";
      classArr[i].style.color = "#fff";
      // this.weightNumber = v.taskItemNo;
    },
    resetItem: function (v) {
      this.testNumber = 0;
      var that = this;
      var params = {
        Token: this.token,
        taskID: v.taskID,
        taskItemNo: Number(v.taskItemNo),
        testID: v.testID,
        recordCode: v.recordCode,
        attributeCode: v.attributeCode,
        recordType: "",
        deviceCode: this.instCode,
        testValue: "",
        sort: Number(v.taskItemNo),
      };
      taskItemWeighAgain(params)
        .then((response) => {
          if (response.ErrorCode == 0) {
            that.onSearch();
          } else {
            Notify({ type: "danger", message: response.ErrorMsg });
          }
        })
        .catch(() => {});
    },
    SaveReckonTaskItemData: function (v, val, isT) {
      var that = this;
      if (val == 0 || val) {
        val = val.toString();
        var params = {
          Token: this.token,
          taskID: v.taskID,
          taskItemNo: Number(v.taskItemNo),
          testID: v.testID,
          recordCode: v.recordCode,
          attributeCode: v.attributeCode,
          recordType: "",
          deviceCode: this.instCode,
          testValue: val,
          sort: Number(v.taskItemNo),
        };
        saveReckonTaskItemData(params)
          .then((response) => {
            if (response.ErrorCode == 0) {
              that.onSearch();
              if (isT == "T") {
                Notify({ type: "success", message: "提交成功！" });
              }
            } else {
              Notify({ type: "danger", message: response.ErrorMsg });
            }
          })
          .catch(() => {});
      } else {
        Notify({ type: "warning", message: "数据不能为空！" });
      }
    },
    saveWeightItem: function (v, val, type, isT) {
      // console.log(v, val, type, isT);
      var that = this;
      var typeCode = "";
      if (val && val != "") {
        val = this.getDecimaZero(val, this.decimalNum);
        if (type == "过程数据") {
          typeCode = 1;
        } else {
          typeCode = 2;
          // var classArr = this.$refs.sampleConfirm;
          var classArr1 = this.$refs.startWeight;
          if (classArr1 && classArr1.length > 0) {
            classArr1.map((item, index) => {
              item.style.background = "#cdcbcb";
              item.style.color = "#323233";
              // classArr1[index].style.background = "#cdcbcb";
              // classArr1[index].style.color = "#323233";
            });
          }
        }
        var params = {
          Token: this.token,
          taskID: v.taskID,
          taskItemNo: Number(v.taskItemNo),
          testID: v.testID,
          recordCode: v.recordCode,
          attributeCode: v.attributeCode,
          recordType: typeCode,
          deviceCode: this.instCode,
          testValue: val,
          sort: Number(v.taskItemNo),
        };
        saveTaskItemData(params)
          .then((response) => {
            if (response.ErrorCode == 0) {
              // if (v.weighMode == "40") {
              //   if (that.testNumber > 3) {
              //     Notify({ type: "success", message: response.ErrorMsg });
              //     if (val && val != "") {
              //       this.SaveReckonTaskItemData(
              //         this.weightItemObj,
              //         this.textValue
              //       );
              //     }
              //   } else {
              //     that.onSearch();
              //   }
              // }
              // if (v.weighMode == "50") {
              //   if (that.testNumber > 4) {
              //     Notify({ type: "success", message: response.ErrorMsg });
              //     if (val && val != "") {
              //       this.SaveReckonTaskItemData(
              //         this.weightItemObj,
              //         this.textValue
              //       );
              //     }
              //   } else {
              //     that.onSearch();
              //   }
              // }
              if (
                v.weighMode == "10" ||
                v.weighMode == "20"
                // ||v.weighMode == "15"
              ) {
                if (that.testNumber == 2) {
                  if (val && val != "") {
                    this.SaveReckonTaskItemData(
                      this.weightItemObj,
                      this.textValue,
                      isT
                    );
                  }
                } else {
                  that.onSearch();
                }
              } else if (v.weighMode == "1" || v.weighMode == "25") {
                if (typeCode == 1) {
                  that.onSearch();
                } else {
                  if (val && val != "") {
                    this.SaveReckonTaskItemData(v, val, isT);
                  }
                }
              }
            } else {
              Notify({ type: "danger", message: response.ErrorMsg });
            }
          })
          .catch(() => {});
      } else {
        Notify({ type: "warning", message: "数据不能为空！" });
      }
    },
    delItem(v, i) {
      var that = this;
      Dialog.confirm({
        message: "确定删除吗？",
      })
        .then(() => {
          var params = {
            Token: this.token,
            AttributeCode: v.attributeCode,
            TaskID: v.taskID,
          };
          DeleteTaskAttribute(params)
            .then((response) => {
              if (response.ErrorCode == 0) {
                that.onSearch();
              }
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    getDecimaZero(number, bitNum) {
      var f_x = parseFloat(number).toFixed(this.decimalNum);
      if (isNaN(f_x)) {
        return 0;
      }
      var s_x = f_x.toString();
      var pos_decimal = s_x.indexOf(".");
      if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += ".";
      }
      while (s_x.length <= pos_decimal + bitNum) {
        s_x += "0";
      }
      return s_x;
    },
    //查询事件
    onSearch(val) {
      var _this = this;
      if (val == "handleSearch") {
        // var classArr = this.$refs.sampleConfirm;
        var classArr1 = this.$refs.startWeight;
        if (classArr1 && classArr1.length > 0) {
          classArr1.map((item, index) => {
            item.style.background = "#cdcbcb";
            item.style.color = "#323233";
            // classArr1[index].style.background = "#cdcbcb";
            // classArr1[index].style.color = "#323233";
            // classArr1[index].disabled = true;
          });
        }
      }
      var itemStr = "";
      if (this.deviceArr.length > 0) {
        itemStr = this.deviceArr.toString();
      }
      var params = {
        Token: this.token,
        search: [this.materialType, this.materialCode, this.batch, itemStr],
      };
      GetTaskItemsTwo(params)
        .then((response) => {
          if (response.ErrorCode == 0) {
            var itemArr = [];
            response.Result.map((item) => {
              if (val == "one") {
                itemArr.push({
                  value: item.attributeCode,
                  text: item.attributeName,
                });
              }
              // Notify({ type: "success", message: response.ErrorMsg });
              if (
                item.weighMode == "10" ||
                item.weighMode == "20"
                // ||item.weighMode == "15"
              ) {
                // item.weighData = [];
                if (item.weighData.length == 0) {
                  item.weighData.push({ testValue: "" });
                  item.weighData.push({ testValue: "" });
                } else if (item.weighData.length == 1) {
                  item.weighData.push({ testValue: "" });
                }
              } else if (item.weighMode == "1" || item.weighMode == "25") {
                if (item.weighData.length == 0) {
                  item.weighData.push({ testValue: "" });
                }
              }
            });
            if (val == "one") {
              _this.deviceItemArr = _this.todo(itemArr, "value");
            }
            this.itemList = response.Result;
          } else {
            Notify({ type: "danger", message: response.ErrorMsg });
          }
        })
        .catch(() => {});
    },
    getItemData() {
      var _this = this;
      var q = {
        queryModel: {
          Token: this.token,
          Code: this.materialCode,
        },
      };
      GetAttributesByMaterialCode(q)
        .then((response) => {
          if (response.ErrorCode == 0) {
            var res = response.Result;
            if (res && res.length > 0) {
              res.map((item) => {
                item.value = item.attributeCode;
                item.text = item.attributeName;
              });
              _this.deviceItemArr = res;
            }
          }
        })
        .catch(() => {});
    },
    updataDeviceItemCode: function (code) {
      this.deviceArr = [];
      if (code && code.length > 0) {
        code.map((item) => {
          this.deviceArr.push(item.value);
        });
      }
    },
    getBatchData: function (val) {
      var _this = this;
      var params = {
        Token: this.token,
        search: ["", val, "", ""],
      };
      GetTaskBatchIDs(params)
        .then((response) => {
          if (response.ErrorCode == 0) {
            _this.batchIdArr = response.Result;
          }
        })
        .catch(() => {});
    },
    updataBatch: function (val) {
      this.batch = val;
    },
    todo: function (arr, key) {
      let set = [];
      let result = [];
      for (let val of arr) {
        if (!set.includes(val[key])) {
          result.push(val);
          set.push(val[key]);
        }
      }
      return result;
    },
  },
  destroyed() {
    // 销毁监听
    if (typeof this.socket.close == "function") {
      this.socket.close();
    }
  },
};
</script>
<style>
.van-nav-bar__title {
  color: #fff;
}
/* .van-icon-arrow-left {
  color: #fff !important;
} */
.van-cell__title {
  text-align: left;
  font-weight: 500;
}
.van-dropdown-menu__bar {
  box-shadow: 0 0 0;
  height: 36px;
}
.item-style .van-row .van-col .van-field__control {
  text-align: center;
}
</style>
<style scoped lang="less">
.weightItem {
  height: 100%;
  overflow-y: hidden;
  margin: 0;
  padding: 0;
}
.nav-bar {
  background-color: #49bbef;
}
.item-style {
  font-size: 0.34rem;
  height: calc(100% - 40px);
  overflow-y: auto;
}
.scan {
  height: 100%;
  width: 100%;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;

  #bcid {
    width: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 1rem;
    text-align: center;
    color: #fff;
    background: #ccc;
    font-size: 20px;
    z-index: 999;
    .closeModel {
      position: absolute;
      top: 20px;
      right: 20px;
    }
  }
  footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    bottom: 0;
    height: 1rem;
    font-size: 20px;
    button {
      height: 100%;
      width: 100%;
      border: none;
    }
  }
}
/deep/.van-dropdown-menu__title {
  width: 4.6rem;
  height: 0.69rem;
  border: 1px solid #ddd;
  font-size: 0.34rem;
  text-align: center;
  margin-right: 0.21rem;
}
/deep/.van-dropdown-menu__title::after {
  display: none;
}
.deviceStyle /deep/.van-cell__title {
  width: 4.6em;
}
.titleStyle {
  display: flex;
  justify-content: space-between;
}
.controlBtn {
  display: flex;
  align-items: center;
}
.controlBtn button {
  margin-right: 8px;
  height: 22px;
  line-height: 18px;
  font-size: 12px;
  padding: 0 10px;
  border-radius: 3px;
}
.controlBtn button:last-child {
  margin-right: 0;
}
.spanStyle span {
  border: 1px solid #ccc;
  display: inline-block;
  text-align: center;
  width: 200px;
  height: 20px;
}
.spanStyle .van-cell {
  padding-top: 2px;
  padding-bottom: 2px;
}
.style1 {
  display: flex;
  margin-bottom: 5px;
}

/deep/.van-popup {
  overflow-y: hidden !important;
}

button {
  border: none;
  background: #cdcbcb;
}
/deep/.van-dropdown-item {
  top: 3rem !important;
}
/deep/.van-button--danger {
  color: #fff;
  background-color: #ee0a24 !important;
  border: 0.02667rem solid #ee0a24 !important;
}
/deep/.van-search__content {
  padding-left: 0;
}

/deep/.van-search .van-cell {
  background-color: #fff;
}
/deep/.van-swipe-cell__wrapper {
  border-bottom: 1px dashed #969799;
}
.readonly /deep/.van-field__body {
  background: #ddd;
}
/deep/.van-cell {
  padding: 0.2rem 0.4rem;
}
/deep/.van-field__body {
  border-radius: 2px !important;
  border: 1px solid #ddd;
}
/deep/.van-cell {
  font-size: 0.32rem;
}
</style>